package com.taijihuabao.common.activititasklistener.quittasklistener;

import com.taijihuabao.modules.entity.ApprovalEntity;
import com.taijihuabao.modules.entity.ApprovalHistoryEntity;
import com.taijihuabao.modules.entity.DeptUserEntity;
import com.taijihuabao.modules.mapper.ApprovalHistoryMapper;
import com.taijihuabao.modules.mapper.ApprovalMapper;
import com.taijihuabao.modules.mapper.DeptUserMapper;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Wang
 */
@Component
public class AlterListener implements TaskListener {

    @Resource
    ApprovalMapper approvalMapper;
    @Resource
    DeptUserMapper deptUserMapper;
    @Resource
    ApprovalHistoryMapper approvalHistoryMapper;
    @Autowired
    HistoryService historyService;
    @Autowired
    TaskService taskService;

    @Override
    public void notify(DelegateTask delegateTask) {
        //审批id
        String businessKey = delegateTask.getExecution().getProcessInstanceBusinessKey();
        //查询审批单
        ApprovalEntity approvalEntity = approvalMapper.selectById(Long.valueOf(businessKey));

        delegateTask.addCandidateUser(String.valueOf(approvalEntity.getApplyUserId()));
        //拿到申请人部门
        List<DeptUserEntity> deptUserEntities = deptUserMapper.selectDeptByUserId(approvalEntity.getApplyUserId());
        String deptCode = deptUserEntities.get(0).getDeptCode();

        ApprovalHistoryEntity approvalHistoryEntity = AddHistoryUtil.addHistory(delegateTask, approvalEntity, deptCode);
        approvalHistoryMapper.insertApproval(approvalHistoryEntity);
    }
}
